"use strict";
var ki = {//ki里面包含一些可配置项目与工具方法
    status: {ok: '200', error: '300', timeout: '301', forbidden: '403'},
    //json格式化工具
    jsonEval: function(data) {
        try {
            if ($.type(data) == 'string')
                return eval('(' + data + ')');
            else
                return data;
        } catch (e) {
            return {};
        }
    },
    //信息提示方法，不需要确认，默认调用Alertify.js，可修改
    _alert: {
        info: function(msg) {
            Alertify.log.info(msg, 0);
        },
        success: function(msg) {
            Alertify.log.success(msg, 0);
        },
        error: function(msg) {
            Alertify.log.error(msg, 0);
        }
    },
    //信息提示方法，需要确认，默认调用Alertify.js，可修改
    _dialog: {
        confirm: function(msg, okFn, todo) {
            Alertify.dialog.labels.ok = $.tips.ok;
            Alertify.dialog.labels.cancel = $.tips.cancel;
            Alertify.dialog.labels.delete = $.tips.delete;
            $.blockUI();
            Alertify.dialog.confirm("<i class='icon-warning-sign alertify-icon'></i>" + msg, function() {
                $.unblockUI();
                okFn && okFn.call();
            }, function() {
                $.unblockUI();
            }, todo);
        },
        alert: function(msg, okFn) {
            Alertify.dialog.labels.ok = $.tips.ok;
            $.blockUI();
            Alertify.dialog.alert("<i class='icon-warning-sign alertify-icon'></i>" + msg, function() {
                $.unblockUI();
                okFn && okFn.call();
            });
        }
    },
    //默认的ajax错误处理方法
    ajaxError: function(xhr, ajaxOptions, thrownError) {
    	//"<div>" + xhr.responseText + "</div>"
        ki._alert.error("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div>"
                + "<div>ajaxOptions: " + ajaxOptions + "</div>"
                + "<div>thrownError: " + thrownError + "</div>");
    },
    //默认的json类型的返回数据的处理方法
    jsonHandle: function(json) {
        if (json.status === ki.status.error) {
            ki._alert.error(json.message || $.message.error);
        } else if (json.status === ki.status.forbidden) {
            ki._alert.error(json.message || $.message.forbidden);
        } else if (json.status === ki.status.timeout) {
            ki._dialog.alert(json.message || $.message.timeout, function() {
                location.href = "sign-in.html";
            });
        } else if (json.status === ki.status.ok) {
            return true;
        }
        return false;
    },
    //默认的ajax访问成功后的回调函数
    ajaxDone: function(data) {
        if (data.status === undefined && data.message === undefined) {
            ki._alert.error(data.message || $.message.error);
            return false;
        }
        if (ki.dataHandle(data)) {
            ki._alert.success(data.message || $.message.ok);
        }
    },
    //页面初始化方法，在初次加载页面与pjax访问成功后调用，一些需要初始化的jQuery插件请在这里进行初始化
    initUI: function(dom) {
        var $p = $(dom || document);
        $("[data-toggle='tooltip']", $p).tooltip();
    },
    //ki插件初始化方法
    init: function(opts) {
        var _opts = {
            selector: "a[target='pjax']", container: ".content", show: "fade", prefix: "用", suffix: "户"
        };
        $.pjax($.extend(_opts, opts));//初始化pjax
        $.ajaxTodo("a[target='ajaxTodo']");//初始化ajaxTodo
        ki.initUI && ki.initUI(); //初始化UI
        //ki._dialog.alert("msg");
    }
};
//除去pjax外的一些核心方法
(function($) {
    //提示框文本，用于国际化
    $.tips = {ok: "OK", cancel: "Cancel", delete: "Delete", yes: "Yes", no: "No", error: "Error", info: "Information", success: "Success", confirm: "Confirm"};
    //提示信息文本，用于国际化
    $.message = {ok: "Success", error: "Fail", timeout: 'Your Login Already Timeout', forbidden: '403'};
    $.ajaxTodo = function(selector) {
        if (!selector) {
            throw new Error('selector must be set');
        }
        $('body').on('click', selector, function(event) {
            if (this.tagName.toUpperCase() !== 'A') {
                throw new Error('click requires an anchor element');
            }
            var $this = $(this), url = $this.attr('href'), title = $this.attr("title"), todo = $this.attr("todo");
            if (title) {
                ki._dialog.confirm(title, function() {
                    ajaxTodo(url, $this.attr("callback"));
                }, todo && todo === "delete");
            } else {
                ajaxTodo(url, $this.attr("callback"));
            }
            event.preventDefault();
        });
    };
    function ajaxTodo(url, callback) {
        var $callback = callback || ki.ajaxDone;
        if (!$.isFunction($callback))
            $callback = eval('(' + callback + ')');
        $.ajax({
            type: 'POST',
            url: url,
            dataType: "json",
            cache: false,
            success: $callback,
            error: ki.ajaxError
        });
    }
    $.blockUI = function(dom) {
        //TODO 暂时只能全页面覆盖，不需要传值
        return addBlock(dom);
    };
    $.unblockUI = function() {
        return removeBlock();
    };
    $.blockUI.opts = {
        element: null
    };
    function addBlock(dom) {
        return $.blockUI.opts.element = $(dom || "body").append("<div class='blockUI'></div>");
    }
    function removeBlock() {
        $.blockUI.opts.element.children(".blockUI").remove();
        return  $.blockUI.opts.element;
    }
    $._loading = function(dom) {
        return $.blockUI(dom).append('<div class="loading"><div id="circularG">\n\
        <div id="circularG_1" class="circularG"></div><div id="circularG_2" class="circularG">\n\
        </div><div id="circularG_3" class="circularG"></div><div id="circularG_4" class="circularG">\n\
        </div><div id="circularG_5" class="circularG"></div><div id="circularG_6" class="circularG"></div>\n\
        <div id="circularG_7" class="circularG"></div><div id="circularG_8" class="circularG"></div></div></div>');
    };
    $._over = function() {
        return $.unblockUI().children(".loading").remove();
    };
    //扩展string的方法
    $.extend(String.prototype, {
        startsWith: function(pattern) {
            return this.indexOf(pattern) === 0;
        },
        endsWith: function(pattern) {
            var d = this.length - pattern.length;
            return d >= 0 && this.lastIndexOf(pattern) === d;
        },
        isUrl: function() {
            return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
        }
    });
})(jQuery);
